<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>智慧生活推送服务 - 服务号版</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <style>
        /* 保留所有CSS样式 */
    </style>
</head>
<body>
    <!-- 保留所有HTML内容 -->
    
    <script>
        // 使用从后端传递的openid
        const openid = '<%= openid %>';
        const appId = '<%= appId %>';
        const timestamp = '<%= timestamp %>';
        const nonceStr = '<%= nonceStr %>';
        
        // 初始化微信JS-SDK
        wx.config({
            debug: false,
            appId: '<%= appId %>',
            timestamp: '<%= timestamp %>',
            nonceStr: '<%= nonceStr %>',
            signature: '<%= signature %>',
            jsApiList: [
                'checkJsApi',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'hideMenuItems',
                'showMenuItems',
                'hideAllNonBaseMenuItem',
                'showAllNonBaseMenuItem',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getNetworkType',
                'openLocation',
                'getLocation',
                'scanQRCode'
            ]
        });
        
        wx.ready(function() {
            console.log('微信JS-SDK初始化完成');
        });
        
        wx.error(function(res) {
            console.error('微信JS-SDK初始化失败:', res);
        });

        // 提交订阅
        document.getElementById('subscribe-btn').addEventListener('click', async function() {
            const province = document.getElementById('province').value;
            const city = document.getElementById('city').value;
            const time = document.querySelector('input[type="time"]').value;
            const openid = getOpenid();
            
            if (!province || !city) {
                alert('请选择完整的省市区信息');
                return;
            }
            
            // 获取选中的服务
            const selectedServices = [];
            document.querySelectorAll('.service-item.active').forEach(item => {
                selectedServices.push(item.getAttribute('data-service'));
            });
            
            if (selectedServices.length === 0) {
                alert('请至少选择一项订阅服务');
                return;
            }
            
            // 获取自定义标签
            const customTags = [];
            document.querySelectorAll('.tag').forEach(tag => {
                customTags.push(tag.textContent.replace(' ×', ''));
            });

            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
            this.classList.add('loading');
            
            try {
                // 发送订阅请求到后端
                const response = await fetch('/wechat/subscription', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        openid,
                        province,
                        city,
                        services: selectedServices,
                        pushTime: time,
                        customTags
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    // 显示成功消息
                    document.getElementById('success-message').classList.remove('hidden');
                    
                    // 3秒后隐藏成功消息
                    setTimeout(() => {
                        document.getElementById('success-message').classList.add('hidden');
                        this.innerHTML = '<i class="fas fa-check"></i> 保存设置';
                        this.classList.remove('loading');
                    }, 3000);
                } else {
                    alert(result.message || '订阅失败');
                    this.innerHTML = '<i class="fas fa-check"></i> 保存设置';
                    this.classList.remove('loading');
                }
            } catch (err) {
                console.error('订阅请求失败:', err);
                alert('网络错误，请稍后重试');
                this.innerHTML = '<i class="fas fa-check"></i> 保存设置';
                this.classList.remove('loading');
            }
        });

        // 页面切换逻辑
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                
                const tabName = this.getAttribute('data-tab');
                document.querySelectorAll('.page').forEach(page => page.classList.remove('active'));
                document.getElementById(tabName + '-page').classList.add('active');
            });
        });

        // 服务选择交互
        document.querySelectorAll('.service-item').forEach(item => {
            item.addEventListener('click', function() {
                this.classList.toggle('active');
            });
        });
        
        // 省份城市联动
        const cityData = {
            beijing: ["北京市"],
            shanghai: ["上海市"],
            guangdong: ["广州市", "深圳市", "东莞市", "珠海市"],
            zhejiang: ["杭州市", "宁波市", "温州市", "嘉兴市"]
        };
        
        document.getElementById('province').addEventListener('change', function() {
            const citySelect = document.getElementById('city');
            const province = this.value;
            
            citySelect.innerHTML = '<option value="">选择城市</option>';
            
            if (province && cityData[province]) {
                cityData[province].forEach(city => {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;
                    citySelect.appendChild(option);
                });
            }
        });

        // 添加自定义标签
        function addCustomTag() {
            const input = document.getElementById('custom-input');
            const value = input.value.trim();
            
            if (value) {
                const tagsContainer = document.getElementById('custom-tags');
                const tag = document.createElement('div');
                tag.className = 'tag';
                tag.innerHTML = `${value} <i class="fas fa-times" onclick="removeTag(this)"></i>`;
                tagsContainer.appendChild(tag);
                input.value = '';
            }
        }
        
        // 移除标签
        function removeTag(element) {
            element.parentElement.remove();
        }
    </script>
</body>
</html>